import React, { Component } from 'react'
import { connect } from 'react-redux'
import { createContainer } from 'utils/hoc'
import { Form, Row, Input, Radio, Button, Switch, message, Popconfirm, Modal, Table } from 'antd'
import ContentBox from 'components/contentBox'
import CustomTable from 'components/common/table'
import Authorized from 'components/common/authorized'
import { CHECK_STATUE, widgetType } from 'constants'
import PropTypes from 'prop-types'
import Filters from 'components/common/filters'

import Style from './list.css'

const { TextArea } = Input
const layout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 16 }
}

// const formTailLayout = {
//   labelCol: { span: 6 },
//   wrapperCol: { span: 9, offset: 2 }
// }

// const auditRadio = [
//   { label: '不限', value: '' },
//   { label: '已审核', value: 'PASS' },
//   { label: '未审核', value: 'REFUSE' }
// ]

// // 上架状态
// const shelvesRadio = [
//   { label: '不限', value: '' },
//   { label: '已上架', value: '1' },
//   { label: '未上架', value: '0' }
// ]
// // 上新状态
// const newRadio = [
//   { label: '不限', value: '' },
//   { label: '上新中', value: '1' },
//   { label: '非上新', value: '0' }
// ]
// // 推荐状态
// const recommendRadio = [
//   { label: '不限', value: '' },
//   { label: '推荐中', value: '1' },
//   { label: '非推荐', value: '0' }
// ]

const checkColumn = [
  {
    title: '审核时间',
    dataIndex: 'time',
    key: 'time',
    width: 120
  },
  {
    title: '审核人员',
    dataIndex: 'auther',
    key: 'auther',
    width: 120
  },
  {
    title: '审核结果',
    dataIndex: 'result',
    key: 'result',
    width: 120
  },
  {
    title: '反馈详情',
    dataIndex: 'id',
    key: 'id',
    width: 120
  }
]

class list extends Component {
  static propTypes = {
    form: PropTypes.any,
    router: PropTypes.any,
    getGoodsList: PropTypes.func,
    getCategoryOptions: PropTypes.func,
    delGoods: PropTypes.func,
    putAway: PropTypes.func,
    goodsUpdate: PropTypes.func,
    recommendGoods: PropTypes.any,
    auditGoods: PropTypes.any

  }
  constructor (props) {
    super(props)
    this.state = {
      pageNo: 1,
      pageSize: 20,
      params: {
      },
      showAudit: false,
      sorter: {}
    }
    this.handleReset = this.handleReset.bind(this)
    this.handleSubmit = this.handleSubmit.bind(this)
    this.onParamsChange = this.onParamsChange.bind(this)
    this.hideAudit = this.hideAudit.bind(this)
    this.auditSubmit = this.auditSubmit.bind(this)
    this.hideAuditForm = this.hideAuditForm.bind(this)
    this.onSelectChange = this.onSelectChange.bind(this)
    this.putAwayAll = this.putAwayAll.bind(this)
    this.putDownAwayAll = this.putDownAwayAll.bind(this)
    this.recommendGoodsAll = this.recommendGoodsAll.bind(this)
    this.goodsUpdateAll = this.goodsUpdateAll.bind(this)
    this.handleAdd = this.handleAdd.bind(this)
  }

  componentDidMount () {
    this.getDataSource()
    this.props.getCategoryOptions()
  }

  componentWillReceiveProps (nextProps) {
    // if (!this.props.putAwayRequest && nextProps.putAwayRequest) {
    //   message.success('操作成功')
    //   // this.handleSubmit()
    // }

    // if (!this.props.recommendGoodsRequest && nextProps.recommendGoodsRequest) {
    //   message.success('操作成功')
    //   // this.handleSubmit()
    // }

    // if (!this.props.goodsUpdateRequest && nextProps.goodsUpdateRequest) {
    //   message.success('操作成功')
    //   // this.handleSubmit()
    // }

    if (!this.props.delRequest && nextProps.delRequest) {
      message.success('删除成功')
      this.handleSubmit()
    }

    if (!this.props.auditRequest && nextProps.auditRequest) {
      // message.success('审核完成')
      this.setState({
        showAuditForm: false
      })
      // this.handleSubmit()
      this.props.handleAuditEdit({
        auditStatus: this.state.auditStatus,
        index: this.state.auditStatusIndex
      })
    }

    // 审核
    if (!this.props.auditEditRequest && nextProps.auditEditRequest) {
      message.success('操作成功')
    }
  }

  getFilterCols (category, author) {
    return [
      {
        label: '输入搜索',
        id: 'searchField',
        widget: widgetType.input,
        placeholder: '请输入商品货号/商品名称'
      }, {
        label: '创作者',
        id: 'authorName',
        widget: widgetType.input,
        placeholder: '请输入'
      }, {
        label: '商品类型',
        id: 'codePath',
        widget: widgetType.select,
        placeholder: '请选择',
        options: category
      }, {
        label: '审核状态',
        id: 'auditStatus',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '已通过',
          value: 'PASS'
        }, {
          text: '未审核',
          value: 'WAITING'
        }, {
          text: '未通过',
          value: 'REFUSE'
        }]
      }, {
        label: '上架状态',
        id: 'putAway',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '已上架',
          value: '1'
        }, {
          text: '未上架',
          value: '0'
        }]
      }, {
        label: '上新状态',
        id: 'updateFlag',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '上新中',
          value: '1'
        }, {
          text: '非上新',
          value: '0'
        }]
      }, {
        label: '推荐状态',
        id: 'recommendFlag',
        widget: widgetType.select,
        placeholder: '请选择',
        options: [{
          text: '不限',
          value: ''
        }, {
          text: '推荐中',
          value: '1'
        }, {
          text: '非推荐',
          value: '0'
        }]
      }, {
        label: false,
        span: 16,
        key: 'custom',
        widget: 'custom',
        formItemLayout: {},
        render: () => {
          return (
            <>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.handleSubmit}>查询</Button>
              <Button style={{ marginRight: 10 }} onClick={this.handleReset}>重置</Button>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.goodsUpdateAll}>批量上新</Button>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.recommendGoodsAll}>批量推荐</Button>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.putAwayAll}>批量上架</Button>
              <Button type='primary' style={{ marginRight: 10 }} onClick={this.putDownAwayAll}>批量下架</Button>
              {/* <Authorized auth='GOODS:MANAGE:DEL'>
                <Button style={{ marginRight: 10 }} onClick={this.handleSubmit}>批量删除</Button>
              </Authorized> */}
            </>
          )
        }
      }
    ]
  }

  getTableCols () {
    return [
      {
        title: '商品编号',
        dataIndex: 'commodityCode',
        key: 'commodityCode',
        width: 120
      },
      {
        title: '货号',
        dataIndex: 'no',
        key: 'no',
        width: 100,
        sorter: true
      },
      {
        title: '商品图片',
        dataIndex: 'imgUrl',
        key: 'imgUrl',
        width: 80,
        render: text => <img className={Style['image']} src={text} />
      },
      {
        title: '商品名称',
        dataIndex: 'name',
        key: 'name',
        width: 70,
        render: text => {
          return text || '-'
        }
      },
      {
        title: '创作者',
        dataIndex: 'authorName',
        key: 'authorName',
        width: 70,
        render: text => {
          return text || '-'
        }
      },
      {
        title: '价格',
        dataIndex: 'price',
        key: 'price',
        width: 100,
        sorter: true,
        // sorter: (a, b) => a.price - b.price,
        render: text => (text / 100).toLocaleString()
      },
      {
        title: '标签',
        dataIndex: 'label',
        key: 'label',
        width: 80,
        render: (text, record) => {
          return <>
            <div>上架：<Switch size='small' defaultChecked={record.putAway === 1} onChange={(checked) => this.putAway(checked, record.commodityId)} /></div>
            {
              record.putAway === 1 && <>
                <div>上新：<Switch size='small' defaultChecked={record.updateFlag === 1} onChange={(checked) => this.goodsUpdate(checked, record.commodityId)} /></div>
                <div>推荐：<Switch size='small' defaultChecked={record.recommendFlag === 1} onChange={(checked) => this.recommendGoods(checked, record.commodityId)} /></div>
              </>
            }
          </>
        }
      },
      {
        title: '库存',
        dataIndex: 'stock',
        key: 'stock',
        width: 70,
        render: text => {
          return text || '-'
        },
        sorter: true
        // sorter: (a, b) => a.stock - b.stock
      },
      {
        title: '销量',
        dataIndex: 'saleNum',
        key: 'saleNum',
        render: text => {
          return text || '-'
        },
        width: 100,
        sorter: true
        // sorter: (a, b) => a.saleNum - b.saleNum
      },
      {
        title: '审核状态',
        dataIndex: 'auditStatus',
        key: 'auditStatus',
        render: (text, record) => {
          return <div>
            {CHECK_STATUE[text] || '-'}
            {/* {
              text === 'PASS' && <a className={Style['a-btn']} onClick={() => this.showAudit(record.commodityId)}>审核详情</a>
            } */}
          </div>
        },
        width: 100
      },
      {
        title: '操作',
        dataIndex: 'operate',
        key: 'operate',
        width: 130,
        fixed: 'right',
        render: (text, record, index) => {
          return <>
            <div className={Style['a-container']}>
              <a target='_blank' className={Style['a-btn']} href={`/goods/details/${record.commodityId}/details`}>查看</a>
              <a target='_blank' className={Style['a-btn']} href={`/goods/edit/${record.commodityId}/edit`}>编辑</a>
            </div>
            <div className={Style['a-container']}>
              <Authorized auth='GOODS:MANAGE:DEL'>
                <Popconfirm placement='top' title='确认是否删除商品' onConfirm={() => this.handleDelete(record.commodityId)}>
                  <a className={Style['a-btn']}>删除</a>
                </Popconfirm>
              </Authorized>
              <Authorized auth='GOODS:MANAGE:AUDIT'>
                {
                  record.auditStatus === 'WAITING' && <a className={Style['a-btn']} onClick={() => this.handleAudit(record.commodityId, index)}>审核</a>
                }
              </Authorized>
            </div>
          </>
        }
      }
    ]
  }

  handleAdd () {
    this.props.router.push('/goods/add')
  }

  handleSubmit () {
    this.setState({
      selectedRowKeys: [],
      commodityIdList: null
    })
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        for (let key in values) {
          if (!values[key]) {
            delete values[key]
          }
        }
        this.setState({
          params: values
        }, () => {
          this.getDataSource()
        })
      }
    })
  }
  handleReset () {
    // window.location.href = '/goods/list'
    const { form } = this.props
    form.resetFields()
    this.setState({
      pageNo: 1,
      pageSize: 20,
      params: {}
    })
    this.props.getGoodsList({
      pageNo: 1,
      pageSize: 20
    })
  }

  getDataSource = () => {
    const { pageSize, pageNo, sorter, params } = this.state
    this.props.getGoodsList({
      pageSize,
      pageNo,
      ...sorter,
      ...params
    })
  }

  onParamsChange (pagination, filters, sorter) {
    const { order, field } = sorter
    let sorterParams = {}
    if (order) {
      sorterParams = {
        sortField: field,
        sortType: order === 'ascend' ? 1 : 2
      }
    }
    this.setState({
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      sorter: sorterParams
    }, () => {
      this.getDataSource()
    })
  }

  // 删除
  handleDelete (id) {
    this.props.delGoods({
      commodityId: id
    })
  }

  // 上架
  putAway (checked, id) {
    this.props.putAway({
      commodityIdList: [{
        commodityId: id,
        putAway: checked ? 1 : 0
      }]
    })
  }
  // 批量上架
  putAwayAll () {
    const { commodityIdList } = this.state
    if (!commodityIdList) {
      message.warning('请选择商品')
      return
    }
    const list = []

    commodityIdList.map(item => {
      list.push({
        commodityId: item,
        putAway: 1
      })
    })

    this.props.putAway({
      commodityIdList: list
    })
  }

  // 批量下架
  putDownAwayAll () {
    const { commodityIdList } = this.state
    if (!commodityIdList) {
      message.warning('请选择商品')
    }

    const list = []

    commodityIdList.map(item => {
      list.push({
        commodityId: item,
        putAway: 0
      })
    })

    this.props.putAway({
      commodityIdList: list
    })
  }
  // 上新
  goodsUpdate (checked, id) {
    this.props.goodsUpdate({
      commodityIdList: [{
        commodityId: id,
        updateFlag: checked ? 1 : 0
      }]
    })
  }
  // 批量上新
  goodsUpdateAll () {
    const { commodityIdList } = this.state
    if (!commodityIdList) {
      message.warning('请选择商品')
    }

    const list = []

    commodityIdList.map(item => {
      list.push({
        commodityId: item,
        updateFlag: 1
      })
    })

    this.props.goodsUpdate({
      commodityIdList: list
    })
  }
  // 推荐
  recommendGoods (checked, id) {
    this.props.recommendGoods({
      commodityIdList: [{
        commodityId: id,
        recommendFlag: checked ? 1 : 0
      }]
    })
  }
  // 批量推荐
  recommendGoodsAll () {
    const { commodityIdList } = this.state
    if (!commodityIdList) {
      message.warning('请选择商品')
    }

    const list = []

    commodityIdList.map(item => {
      list.push({
        commodityId: item,
        recommendFlag: 1
      })
    })

    this.props.recommendGoods({
      commodityIdList: list
    })
  }

  handleView (id) {
    this.props.router.push(`/goods/details/${id}/details`)
  }

  // 编辑
  handleEdit (id) {
    this.props.router.push(`/goods/edit/${id}/edit`)
  }

  // 审核
  handleAudit (id, index) {
    this.setState({
      goodsId: id,
      showAuditForm: true,
      auditStatusIndex: index
    })
  }

  // 提交审核
  auditSubmit () {
    const { goodsId } = this.state
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        this.props.auditGoods({
          commodityId: goodsId,
          auditStatus: values.modalStatus,
          comment: values.comment
        })
        this.setState({
          auditStatus: values.modalStatus
        })
        delete values.modalStatus
      }
    })
  }

  hideAuditForm () {
    this.setState({
      showAuditForm: false
    })
  }

  showAudit () {
    this.setState({
      showAudit: true
    })
  }

  hideAudit () {
    this.setState({
      showAudit: false
    })
  }

  onSelectChange (selectedRowKeys, selectedRows) {
    let commodityIdList = []
    selectedRows.map(item => {
      commodityIdList.push(item.commodityId)
    })

    this.setState({
      commodityIdList,
      selectedRowKeys
    })
  }

  render () {
    const { pageNo, pageSize, showAudit, selectedRowKeys, showAuditForm } = this.state
    const { getFieldDecorator } = this.props.form
    const { goodsData, categoryOptions, form } = this.props
    const pagination = {
      showSizeChanger: true,
      current: pageNo,
      total: goodsData && goodsData.total,
      pageSize
    }

    return (
      <>
        <ContentBox>
          <div className={Style['scenes-list-container']}>
            <Row>
              <Filters
                cols={this.getFilterCols(categoryOptions)}
                form={form}
                search={this.handleSubmit}
                reset={this.handleReset}
                actions={false}
              >
                <div className={Style['button-container']}>
                  <Button type='primary' style={{ marginLeft: '10px' }} onClick={this.goodsUpdateAll}>批量上新</Button>
                  <Button type='primary' style={{ marginLeft: '10px' }} onClick={this.recommendGoodsAll}>批量推荐</Button>
                  <Button type='primary' style={{ marginLeft: '10px' }} onClick={this.putAwayAll}>批量上架</Button>
                  <Button type='primary' style={{ marginLeft: '10px' }} onClick={this.putDownAwayAll}>批量下架</Button>
                  <Authorized auth='GOODS:MANAGE:DEL'>
                    <Button style={{ marginLeft: '10px' }} onClick={this.handleSubmit}>批量删除</Button>
                  </Authorized>
                </div>
              </Filters>
            </Row>
            <Row>
              <CustomTable
                selectedRowKeys={selectedRowKeys}
                multipleSelect={this.onSelectChange}
                multiple
                loading={!goodsData}
                columns={this.getTableCols()}
                dataSource={(goodsData && goodsData.list) || []}
                pagination={pagination}
                onChange={this.onParamsChange}
                scroll={{ x: 1600 }}
              />
            </Row>
            <Modal
              title='审核详情'
              visible={showAudit}
              width={600}
              onOk={this.hideAudit}
              onCancel={this.hideAudit}>
              <Table columns={checkColumn} />
            </Modal>
            <Modal
              title='审核'
              destroyOnClose
              visible={showAuditForm}
              width={600}
              onOk={this.auditSubmit}
              onCancel={this.hideAuditForm}>
              <Form {...layout} >
                <Form.Item label='是否通过'>
                  {
                    getFieldDecorator('modalStatus', {
                      // rules: [{ required: true, message: '请选择' }]
                    })(
                      <Radio.Group>
                        <Radio value='PASS'>通过</Radio>
                        <Radio value='REFUSE'>不通过</Radio>
                      </Radio.Group>
                    )
                  }

                </Form.Item>
                <Form.Item label='审核意见'>
                  {
                    getFieldDecorator('comment')(
                      <TextArea placeholder='请输入' />
                    )
                  }

                </Form.Item>
              </Form>
            </Modal>
          </div>
        </ContentBox>
      </>
    )
  }
}

const mapState = state => ({
  goodsData: state.goods.goodsData,
  delRequest: state.goods.delRequest,
  auditRequest: state.goods.auditRequest,
  putAwayRequest: state.goods.putAwayRequest,
  recommendGoodsRequest: state.goods.recommendGoodsRequest,
  goodsUpdateRequest: state.goods.goodsUpdateRequest,
  categoryOptions: state.goods.categoryOptions,
  auditEditRequest: state.goods.auditEditRequest
})
const mapDispatch = dispatch => ({
  getGoodsList: dispatch.goods.getGoodsList,
  delGoods: dispatch.goods.delGoods,
  putAway: dispatch.goods.putAway, // 上架
  recommendGoods: dispatch.goods.recommendGoods, // 推荐
  goodsUpdate: dispatch.goods.goodsUpdate, // 上新
  auditGoods: dispatch.goods.auditGoods,
  getCategoryOptions: dispatch.goods.getCategoryOptions,
  handleAuditEdit: dispatch.goods.handleAuditEdit
})
const Formlist = Form.create()(list)

export default createContainer(
  connect(
    mapState,
    mapDispatch
  )(Formlist)
)
